/*
 ============================================================================
 Name        : mysql_util.c
 Author      : ljf
 Version     :
 Copyright   : Your copyright notice
 Description : Connect Mysql utils
 History     : 2020/01/15 init versoin
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "mysql_util.h"
#include "sysinfo.h"
#include "ljf_util.h"

MYSQL *g_conn;
MYSQL_RES *g_res;
MYSQL_ROW g_row;

#define MAX_BUF_SIZE 1024

void print_mysql_error(const char *msg) {
    if (msg)
        printf("%s: %s\n", msg, mysql_error(g_conn));
    else
        puts(mysql_error(g_conn));
}

static int executesql(const char * sql) {
    /*query the database according the sql*/
	//printf("[SQL] : [%s]\n",sql);
    if (mysql_real_query(g_conn, sql, strlen(sql)))
    {
    	printf("[ERROR] exec sql failed,sql:%s\n",sql);
        return -1;
    }

    return 0;
}

int list_info()
{
	char sql[MAX_BUF_SIZE];
	int len = 0;
	len = sprintf(sql,"SELECT * FROM `%s`",TABLE_SYSTEM_INFO_NAME);
	
    if (executesql(sql))
    {
        print_mysql_error(NULL);
    }

	g_res = mysql_store_result(g_conn);

	int iNum_rows = mysql_num_rows(g_res);
    int iNum_fields = mysql_num_fields(g_res);



    while ((g_row=mysql_fetch_row(g_res))){
		
        printf("%s\t%s\t%s\t%s\t%s\t%s\t%s\n", g_row[17],g_row[1], g_row[2],g_row[4],g_row[3],g_row[12],g_row[15]);
    }

    mysql_free_result(g_res);

}

/*

db struct:
`user` float(6,2) NOT NULL COMMENT 'us',
`system` float(6,2) NOT NULL COMMENT 'sy',
`nice` float(6,2) NOT NULL COMMENT 'ni',
`idle` float(6,2) NOT NULL COMMENT 'id',
`wait` float(6,2) NOT NULL COMMENT 'wa',
`hardirq` float(6,2) NOT NULL COMMENT 'hi',
`softirq` float(6,2) NOT NULL COMMENT 'si',
`steal` float(6,2) NOT NULL COMMENT 'st',
`freeram` bigint(19) NOT NULL COMMENT 'freeram',
`sharedram` bigint(19) NOT NULL COMMENT 'sharedram',
`bufferram` bigint(19) NOT NULL COMMENT 'bufferram',
`totalram` bigint(19) NOT NULL COMMENT '内存总量',
`ramusage` float(6,2) NOT NULL COMMENT '内存使用率',
`diskavail` bigint(19) NOT NULL COMMENT '硬盘可用',
`disktotal` bigint(19) NOT NULL COMMENT '硬盘大小',
`diskusage` float(6,2) NOT NULL COMMENT '硬盘使用率',

*/

int add_info(sysInfo_type *s)
{
	int ret = 0;
	char sql[MAX_BUF_SIZE] = {0};
	char timeStamp[32]={0};
	time_t now;
	struct tm *timenow;

	time(&now);
	timenow = localtime(&now);
	sprintf(timeStamp,"%04d-%02d-%02d %02d:%02d:%02d",
				(timenow->tm_year+1900),
				(timenow->tm_mon+1),
				timenow->tm_mday,
				(timenow->tm_hour),
				(timenow->tm_min),
				(timenow->tm_sec));
	//printf("Local time:%s\n",timeStamp);
	int len = sprintf(sql, 
			"INSERT INTO `%s` (%s) VALUES (%.02f,%.02f,%.02f,%.02f,%.02f,%.02f,%.02f,%.02f,%lu,%lu,%lu,%lu,%.02f,%llu,%llu,%.02f,'%s')",
				TABLE_SYSTEM_INFO_NAME,
				TABLE_SYSTEM_INFO_FIELD,
				s->cpu_usage.us,
				s->cpu_usage.si,
				s->cpu_usage.ni,
				s->cpu_usage.id,
				s->cpu_usage.wa,
				s->cpu_usage.hi,
				s->cpu_usage.si,
				s->cpu_usage.st,
				s->mem_usage.freeram,
				s->mem_usage.sharedram,
				s->mem_usage.bufferram,
				s->mem_usage.totalram,
				s->mem_usage.usedRate,
				s->disk_use.diskAvail,
				s->disk_use.diskTotal,
				s->disk_use.useRate,
				timeStamp
				);
	
    if (executesql(sql))
    {
		print_mysql_error("add system info failed!!\n");
		ret = -1;
	}
    return ret;
}

/*
	function init_mysql()

*/ 
int init_mysql()
{ 
    // init the database connection
    g_conn = mysql_init(NULL);
    mysql_query(g_conn,"set names utf-8");
    /* connect the database */
    if(!mysql_real_connect(g_conn, DB_HOST, DB_USR, DB_PWD, DB_NAME, DB_PORT, NULL, 0))
    {
    	printf("connect failed!!\n");
        return -1;
    }
	printf("Connect to host:%s,database:%s\n",DB_HOST,DB_NAME);
    return 0;
}

int deinit_mysql()
{
	mysql_close(g_conn);
}

